import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LXW
 * Date: 2022-03-17
 * Time: 18:41
 */
public class TestInsert {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        // 创建数据库
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java102?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("111111");
        // 代码与数据库连接
        Connection connection = dataSource.getConnection();
        // 从控制台输入数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你的id");
        int id = scanner.nextInt();
        System.out.println("请输入你的name");
        String name = scanner.nextLine();
        // 编写sql语句
        String sql = "insert into student values (?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);
        System.out.println("statement: "+ statement);
        // 执行sql
        int ret = statement.executeUpdate();
        System.out.println(ret);
        // 释放资源
        statement.close();
        connection.close();
    }
}
